package com.jp.knowledge.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.activity.JpMainActivity;
import com.jp.knowledge.activity.SearchActivity;
import com.jp.knowledge.activity.SkillDetailActivity;
import com.jp.knowledge.adapter.skill.SkillHeadAdapter;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.SkillModel;
import com.jp.knowledge.my.base.RecycleVAdapter;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.view.JpRecycleView;
import com.jp.knowledge.view.SkillContentView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 528787067@qq.com on 2017/4/18.
 */

public class SkillFragment extends BaseFragment implements SkillContentView.OnItemClickListener, RecycleVAdapter.OnItemClickListener {

    private static final int GET_SKILL_CODE = 0x01;

    private Context mContext;
    private View contentView;
    private JpRecycleView skillHeadView;
    private LinearLayout skillContentView;

    private FileCacheManager fileCacheManager;
    private SkillModel skillModel;
    private int currentPosition;

    private SkillHeadAdapter skillHeadAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(contentView == null) {
            mContext = getContext();
            fileCacheManager = new FileCacheManager();
            currentPosition = 0;

            contentView = View.inflate(mContext, R.layout.fragment_skill, null);
            skillHeadView = (JpRecycleView) contentView.findViewById(R.id.skill_head_view);
            skillContentView = (LinearLayout) contentView.findViewById(R.id.skill_content_view);

            skillHeadView.setHasFixedSize(true);
            skillHeadView.setLayoutManager(new GridLayoutManager(mContext, 4){
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            });
            skillHeadAdapter = new SkillHeadAdapter(mContext, new ArrayList<SkillModel.CategoryBean>());
            skillHeadAdapter.addItemClickListener(this);
            skillHeadView.setAdapter(skillHeadAdapter);
            initHead(contentView);
            readCache(null);
        }
        return contentView;
    }

    @Override
    protected void initHead(View mView) {
        super.initHead(mView);
        topName.setText("岗位知识");
        rightIcon.setVisibility(View.VISIBLE);
        rightIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =new Intent(mContext, SearchActivity.class);
                intent.putExtra("id",skillModel.getCategory().get(currentPosition).getId());
                intent.putExtra("action",2);
                intent.putExtra("level",1);
                mContext.startActivity(intent);
            }
        });
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            View topBar = contentView.findViewById(R.id.top_bar);
//            int statusBarHeight = 0;
//            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
//            if (resourceId > 0)
//                statusBarHeight = getResources().getDimensionPixelSize(resourceId);
//            topBar.setPadding(0, statusBarHeight, 0, 0);
//        }
    }

    private void setView(SkillModel skillModel){
        skillHeadAdapter.updateAdapter(skillModel.getCategory());
        List<SkillModel.ListsBean> listsBean = skillModel.getLists();
        skillContentView.removeAllViews();
        for(int i = 0, j = listsBean.size(); i < j; i++){
            SkillContentView view = new SkillContentView(mContext);
//            view.setData(listsBean.get(i), i);
            view.setOnItemClickListener(this);
            skillContentView.addView(view);
        }
    }

    private void readCache(final String id){
        Observable.create(new Observable.OnSubscribe<SkillModel>() {
            @Override
            public void call(Subscriber<? super SkillModel> subscriber) {
                SkillModel data = (SkillModel) fileCacheManager.readObject(getCachePath(id));
                subscriber.onNext(data);
            }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<SkillModel>() {
            @Override
            public void onCompleted() {
                // 缓存超过10分钟则重新获取数据
                if(skillModel == null || System.currentTimeMillis()-skillModel.getCacheTime() > 1000*60*10)
                    getData(id);
            }
            @Override
            public void onError(Throwable e) {
                onCompleted();
            }
            @Override
            public void onNext(SkillModel data) {
                skillModel = data;
                setView(data);
                onCompleted();
            }
        });
    }

    private void getData(final String id){
        JsonObject param = new JsonObject();
        if(id != null)
            param.addProperty("id", id);
        HttpHelper.getInstance(mContext).getSkill(param, GET_SKILL_CODE, new ResultSubscriber.OnResultListener() {
            @Override
            public void onStart(int requestType) {}
            @Override
            public void onCompleted(int requestType) {}
            @Override
            public void onError(int requestType) {
                onCompleted(requestType);
            }
            @Override
            public void onNext(IModel data, int requestType) {
                if(data.getErrcode() != 0){
                    ToasUtil.toast(mContext, data.getMessage());
                    onError(requestType);
                } else if(requestType == GET_SKILL_CODE){
                    skillModel = data.getEntity(SkillModel.class);
                    setView(skillModel);
                    skillModel.setCacheTime(System.currentTimeMillis());
                    saveCache(skillModel, getCachePath(id));
                }
            }
        });
    }

    private void saveCache(final Object data, final String path){
        new Thread(new Runnable() {
            @Override
            public void run() {
                fileCacheManager.wirteObject(data, path);
            }
        }).start();
    }

    private String getCachePath(String id){
        return mContext.getCacheDir() + "/skillCache_" + id + ".dat";
    }

    /* 一级分类单击回调 */
    @Override
    public void itemSelect(int position) {
        if(currentPosition == position)
            return;
        try {
            skillContentView.removeAllViews();
            readCache(skillModel.getCategory().get(position).getId());
        } catch (Exception e){}finally {
            currentPosition = position;
            skillHeadAdapter.setSelectPosition(currentPosition);
            skillHeadAdapter.notifyDataSetChanged();
        }
    }

    /* 二级分类单击回调 */
    @Override
    public void onItemClick(int mainPosition, int subPosition) {
        List<SkillModel.ListsBean> data = skillModel.getLists();
        startActivity(new Intent(mContext, SkillDetailActivity.class)
                .putExtra("data", (Serializable) data)
                .putExtra("mainPosition", mainPosition)
                .putExtra("subPosition", subPosition)
                .putExtra("id",skillModel.getCategory().get(currentPosition).getId()));
    }
}
